package org.foreningsgatan.mercenaries.manual.generator;

import java.util.Random;

import org.foreningsgatan.modular.terrain.model.SimpleMap;

/**
 * 
 * Copyright (c) 2008 Joakim Back
 * 
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to deal
 * in the Software without restriction, including without limitation the rights
 * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
 * copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 * 
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 * 
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
 * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
 * SOFTWARE.
 * 
 * @author Joakim Back
 * 
 */
public class MapGenerator {
	public static Random sRANDOM = new Random();

	private static void grow(SimpleMap map, Object baseObj) {
		SimpleMap copy = copy(map);

		for (int x = 1; x < map.getSize() - 1; x++) {
			for (int y = 1; y < map.getSize() - 1; y++) {
				Object obj = copy.get(x, y);

				if (obj == baseObj) {
					continue;
				}

				if (sRANDOM.nextBoolean())
					map.set(x - 1, y, obj);
				if (sRANDOM.nextBoolean())
					map.set(x + 1, y, obj);
				if (sRANDOM.nextBoolean())
					map.set(x, y - 1, obj);
				if (sRANDOM.nextBoolean())
					map.set(x, y + 1, obj);
			}
		}

		return;
	}

	private static void randomSeed(SimpleMap map, Object[] objects) {
		int size = map.getSize();

		int x = sRANDOM.nextInt(size);
		int y = sRANDOM.nextInt(size);

		Object obj = objects[sRANDOM.nextInt(objects.length)];

		map.set(x, y, obj);
	}

	private static SimpleMap copy(SimpleMap map) {
		int size = map.getSize();

		SimpleMap copy = new SimpleMap(size);

		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				copy.set(x, y, map.get(x, y));
			}
		}

		return copy;
	}

	public static SimpleMap generate(int size, Object[] objects) {
		SimpleMap map = new SimpleMap(size);

		for (int x = 0; x < size; x++) {
			for (int y = 0; y < size; y++) {
				map.set(x, y, objects[0]);
			}
		}

		double factor = (size * size) / (32 * 32);

		for (int i = 0; i < 50 * factor; i++) {
			randomSeed(map, objects);
		}

		for (int i = 0; i < 5; i++) {
			grow(map, objects[0]);
		}

		return map;
	}
}
